# encoding: utf-8

class GroupsPostsController < ApplicationController
	
	before_filter :load_sidebar
  before_filter :require_login
  def show
    @groups_post = GroupsPost.find(params[:id])

    # prekini izvodjenje ako nema dopustenja (inace dolazi do double render errora)
    return unless require_group_permission(@groups_post.groups_thread.group)
  end

  # GET /groups_posts/new
  # GET /groups_posts/new.xml
  def new
    @groups_post = GroupsPost.new
    @groups_post[:groups_thread_id] = params[:thread_id]
    @thread = GroupsThread.find(@groups_post.groups_thread_id)
    
    # handle quoting
    unless params[:thread].nil? or params[:quote].nil?
  		if params[:thread] == 'true'
  			quoted_post = GroupsThread.find(params[:quote])
  		else
  			quoted_post = GroupsPost.find(params[:quote])
  		end
    	quoted_post_content = quoted_post.content.gsub(/\[quote=?(.*?)\](.*?)\[\/quote\]/, "") # onemogucavanje nestanja quoteova
    	@groups_post.content = "[quote=#{quoted_post.member.username}]#{quoted_post_content}[/quote]";
  	end
    
  end

  # GET /groups_posts/1/edit
  def edit
    @groups_post = GroupsPost.find(params[:id])
    return unless require_admin_or_this_member @groups_post.member
  end

  # POST /groups_posts
  # POST /groups_posts.xml
  def create
    @groups_post = GroupsPost.new(params[:groups_post])
    @groups_post[:member_id] =  current_member.id

    if @groups_post.save
      @groups_post.groups_thread.recount
      
      feed = Feed.new
      feed.content = @groups_post
      feed.member = current_member
      feed.group = @groups_post.groups_thread.group
      feed.save
      
      redirect_to(@groups_post.groups_thread, :notice => 'Poslano!')
    else
      render :action => "new"
    end
  end

  # PUT /groups_posts/1
  # PUT /groups_posts/1.xml
  def update
    @groups_post = GroupsPost.find(params[:id])
    return unless require_admin_or_this_member @groups_post.member

    if @groups_post.update_attributes(params[:groups_post])
      redirect_to(@groups_post.groups_thread, :notice => 'Post je updatean.')
    else
      render :action => "edit"
    end

  end

  # DELETE /groups_posts/1
  # DELETE /groups_posts/1.xml
  def destroy
    @groups_post = GroupsPost.find(params[:id])
    return unless require_moderator_or_this_member @groups_post.member

    redirect_url = @groups_post.groups_thread
    groups_thread = @groups_post.groups_thread

    @groups_post.destroy
    groups_thread.recount

    redirect_to(redirect_url)
  end
end
